﻿using System;
using System.IO;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading;
using ExcelRefresh.Com;
using Microsoft.Office.Interop.Excel;
//using Microsoft.Office.Tools.Excel;
using Microsoft.Office.Core;
using Action = System.Action;
using MsoDocProperties = Microsoft.Office.Core.MsoDocProperties;

namespace ExcelRefresh.Excel
{
        public class RefreshableProxy
        {
            public RefreshableProxy(OLEDBConnection connection, string name)
            {
                _refresh = () => connection.Refresh();
                _isRefreshing = () => connection.Refreshing;
                Name = "OleDB connection: " + name;
            }

            public RefreshableProxy(ODBCConnection connection, string name)
            {
                _refresh = () => connection.Refresh();
                _isRefreshing = () => connection.Refreshing;
                Name = "ODBC connection: " + name;
            }

            public RefreshableProxy(QueryTable queryTable, string name)
            {
                _refresh = () => queryTable.Refresh();
                _isRefreshing = () => queryTable.Refreshing;
                Name = "Query Table: " + name;
            }

            public RefreshableProxy(PivotTable pivotTable, string name)
            {
                var startTime = DateTime.Now.AddSeconds(-60);
                _refresh = () =>
                {
                    if (pivotTable.RefreshDate < startTime)
                        pivotTable.RefreshTable();
                    pivotTable.Update();
                };

                _isRefreshing = () => false;
                Name = name;
            }

            public RefreshableProxy(PivotCache cache, string name)
            {
                var startTime = DateTime.Now.AddSeconds(-60);
                _refresh = () =>
                {
                    try
                    {
                        if (cache.RefreshDate < startTime)
                            cache.Refresh();
                        cache.ResetTimer();
                    }
                    catch (Exception)
                    {   // don't throw, since this is usually an irrepairable and unimportant error
                        Trace.TraceWarning("{0} - {1}", cache, name);
                    }
                };
                _isRefreshing = () => false;
                Name = name;
            }

            private readonly Func<bool> _isRefreshing;
            private readonly Action _refresh;

            public void Refresh() { _refresh(); }
            public bool IsRefreshing { get { return _isRefreshing(); } }
            public string Name { get; set; }
        }
}
